package jmind.core.aspect;

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jmind.core.log.LogUtil;
import jmind.base.util.GlobalConstants;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

/**
 * 全局异常拦截
 *  http://www.360doc.com/content/12/0710/15/4280915_223391892.shtml  http://blog.csdn.net/sd0902/article/details/18660339
 *  http://zhidao.baidu.com/link?url=TqV6xJ9BhDArJ8jLDAzC9jlfu_3FkBgSOnEpcFHu_dCFinxRBY5ULBLC4dT2cLxYbqYYvrWNiosg4jYasmbxTq
 *   ExceptionHandler(Throwable.class) 注解形式和配置不能共存,直接用write 输出不会有乱码，返回String在tomcat下有乱码
 * 配置文件配置
 *  <bean  class="com.letv.boss.api.controller.ExceptionHandlerExceptionResolver"></bean>
 * @author xieweibo
 * @date 2015年9月25日
 */
public class ExceptionHandlerExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception e) {
        LogUtil.error(e);
        //        ModelAndView modelAndView = new ModelAndView("500");
        //
        //        modelAndView.addObject("codeMsg", new CodeMsg(9998, ex.getMessage()));
        //
        //        return modelAndView;

        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding(GlobalConstants.UTF8);
        JSONObject jo = new JSONObject();
        jo.put("code", 9999);
        jo.put("msg", e.getMessage());
        try {
            request.setCharacterEncoding(GlobalConstants.UTF8);
            response.getWriter().write(jo.toJSONString());
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return null;
    }

}
